package com.skwyb.form.service.admin;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skwyb.form.bean.dto.SysRole;
import com.skwyb.form.bean.dto.SysRoleAdmin;
import com.skwyb.form.bean.dto.SysRoleFun;
import com.skwyb.form.bean.req.admin.GetRoleResp;
import com.skwyb.form.bean.req.admin.SaveRoleReq;
import com.skwyb.form.mapper.SysRoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class RoleService extends ServiceImpl<SysRoleMapper, SysRole> {

    private final RoleFunService roleFunService;
    private final RoleAdminService roleAdminService;

    /**
     * 查询角色
     *
     * @param record role
     * @return role
     */
    public GetRoleResp selectRole(SysRole record) {
        SysRole role = getById(record.getId());
        GetRoleResp resp = new GetRoleResp();
        BeanUtils.copyProperties(role, resp);

        resp.setMenuIds(roleFunService.getMenuIds(role.getId()));
        resp.setAdminIds(roleAdminService.getAdminIds(role.getId()));
        return resp;
    }

    /**
     * 保存角色
     *
     * @param req role
     * @return row
     */
    @Transactional
    public boolean saveRole(SaveRoleReq req) {
        boolean result;
        SysRole record = new SysRole();
        BeanUtils.copyProperties(req, record);
        result = super.save(record);
        log.info("==> save SysRole execute result={}", result);

        roleFunService.remove(Wrappers.lambdaQuery(new SysRoleFun().setRoleId(record.getId())));

        List<SysRoleFun> roleFunList = new ArrayList<>();
        for (String s : req.getMenuIds().split(",")) {
            SysRoleFun roleFun = new SysRoleFun();
            roleFun.setRoleId(record.getId());
            roleFun.setFunId(s);
            roleFunList.add(roleFun);
        }
        boolean b = roleFunService.saveBatch(roleFunList);
        log.info("==> saveBatch SysRoleFun execute result={}", b);

        roleAdminService.remove(Wrappers.lambdaQuery(new SysRoleAdmin().setRoleId(record.getId())));
        List<SysRoleAdmin> roleAdminList = new ArrayList<>();
        for (String s : req.getAdminIds().split(",")) {
            SysRoleAdmin roleAdmin = new SysRoleAdmin();
            roleAdmin.setRoleId(record.getId());
            roleAdmin.setAdminId(s);
            roleAdminList.add(roleAdmin);
        }
        boolean b1 = roleAdminService.saveBatch(roleAdminList);
        log.info("==> saveBatch SysRoleAdmin execute result={}", b1);
        return result;
    }
}
